import {
  indexApi
} from '../../../api/index';
import {
  request
} from '../../../utils/request';
Page({
  data: {
    defaultData: {
      title: "订单详情", // 导航栏标题
      imageSrc: "/images/back.png",
      isBackToPreviousPage: true
    },
    satisfiedOptions: [{
        text: "礼貌热情",
        selected: false
      },
      {
        text: "风雨无阻",
        selected: false
      },
      {
        text: "技术专业",
        selected: false
      },
      {
        text: "穿戴整齐",
        selected: false
      },
      {
        text: "准时完成",
        selected: false
      },
      {
        text: "沟通愉快",
        selected: false
      }
    ],
    notSatisfiedOptions: [{
        text: "服务态度差",
        selected: false
      },
      {
        text: "迟到早退",
        selected: false
      },
      {
        text: "技术不专业",
        selected: false
      },
      {
        text: "沟通困难",
        selected: false
      },
      {
        text: "态度不好",
        selected: false
      },
      {
        text: "做事拖拉",
        selected: false
      }
    ],
    selectedOptions: "",
    isSatisfied: true, // 默认显示满意选项
    satisfiedFlag:1,//满意不满意
    subSelectMsg:"",//拼接的选项
    subMessage:"",//输入的师傅评价
    moreEvaluation:"",//输入商品评价
    totalEvaluation:null,//总体满意度
    checked: true, //匿名
    anonymousFlag:1,//匿名
    overallSatisfaction: 0, //总体满意度
    serviceSatisfaction: 0, //服务满意度
    productSatisfaction: 0, //商品满意度
    overallEvaluate: '',
    serviceEvaluate: '',
    productEvaluate: '',
    fileList: [], //图片上传
    evaluationImgUrl:"",//拼接的图片地址
    orderId:null,
    order:{},
    worker:{}
  },
  onLoad(options) { 
    const order = JSON.parse(decodeURIComponent(options.order)); 
    console.log("options.orderId",order); 
    
    const worker=order.reviceOrders[0] //工人信息
    console.log("worker",worker);
    this.setData({
      orderId:order.orderId,
      order:order,
      worker:worker
    })
  },

  // 工人的输入评价
  onInput: function(event) {
    const value = event.detail.value;
    this.setData({
      subMessage: value,
    });
    console.log("subMessage",event.detail.value);
  },
  //商品评价输入
  productInput(event){
    const value = event.detail.value;
    this.setData({
      moreEvaluation: value,
    });
    console.log("moreEvaluation",event.detail.value);
  },

  //匿名
  onChange(event) {
    this.setData({
      checked: event.detail,
    });
    if (event.detail == true) {
      this.setData({
        anonymousFlag:1
      })
    } else {
      this.setData({
        anonymousFlag:0
      })
    }
    console.log("anonymousFlag",this.data.anonymousFlag);
  },

  //满意度星星
  onRateChange(event) {
    const value = event.detail;
    const type = event.currentTarget.dataset.type;
    // console.log("event", value);
    // console.log("event.currentTarget.dataset", type);
    let evaluate = '';
    if (value == 1) {
      console.log("非常不满意", value);
      evaluate = '非常不满意';
    } else if (value == 2) {
      evaluate = '不满意';
    } else if (value == 3) {
      evaluate = '一般';
    } else if (value == 4) {
      evaluate = '满意';
    } else if (value == 5) {
      evaluate = '非常满意';
    }

    if (type == 'overall') {
      console.log("overallSatisfaction", evaluate);
      this.setData({
        overallSatisfaction: value,
        overallEvaluate: evaluate
      });
    } else if (type == 'service') {
      console.log("serviceSatisfaction", evaluate);
      this.setData({
        serviceSatisfaction: value,
        serviceEvaluate: evaluate
      });
    } else if (type == 'product') {
      console.log("serviceSatisfaction", evaluate);
      this.setData({
        productSatisfaction: value,
        productEvaluate: evaluate
      });
    }
  },

  // 满意不满意
  handleSatisfied: function () {
    this.setData({
      isSatisfied: true,
      satisfiedFlag:1,
      notSatisfiedOptions: this.data.notSatisfiedOptions.map(option => ({ ...option, selected: false }))
    });
    this.updateSelectedOptions();
  },

  handleUnsatisfied: function () {
    this.setData({
      isSatisfied: false,
      satisfiedFlag:2,
      satisfiedOptions: this.data.satisfiedOptions.map(option => ({ ...option, selected: false }))
    });
    this.updateSelectedOptions();
  },

  handleOptionClick: function (e) {
    const {
      index
    } = e.currentTarget.dataset;
    const listKey = this.data.isSatisfied ? 'satisfiedOptions' : 'notSatisfiedOptions';
    const newList = this.data[listKey].map((option, idx) => ({
      ...option,
      selected: idx === index ? !option.selected : option.selected,
    }));
    this.setData({
      [listKey]: newList
    });
    this.updateSelectedOptions();
  },

  updateSelectedOptions: function () {
    const listKey = this.data.isSatisfied ? 'satisfiedOptions' : 'notSatisfiedOptions';
    const selectedTexts = this.data[listKey]
      .filter(option => option.selected)
      .map(option => option.text)
      .join(', ');
    console.log(selectedTexts);
    this.setData({
      subSelectMsg:selectedTexts
    })
  },

  //上传图片
  afterRead(event) {
    const {
      file
    } = event.detail;
    this.uploadFile(file);
  },

  // 文件超出大小限制处理函数
  onOversize(event) {
    wx.showToast({
      title: '文件大小超出限制',
      icon: 'none'
    });
  },

  // 上传图片
  async uploadFile(file) {
    try {
      const uploadTask = wx.uploadFile({
        url: indexApi.upLoadApi(),
        header: {
          "Content-Type": "multipart/form-data"
        },
        filePath: file.url,
        name: 'file',
        formData: {

        },
        success: (res) => {
          const data = JSON.parse(res.data);
          console.log('Upload success', data);
          this.setData({
            fileList: [...this.data.fileList, file]
          });
          console.log("fileList",this.data.fileList);
          this.concatenateImageUrls();
        },
        fail: (err) => {
          console.error('Upload failed', err);
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          });
        }
      });
    } catch (error) {
      console.error("Error:", error);
    }
  },

  // 删除图片
  onDelete(event) {
    const {
      index
    } = event.detail;
    const {
      fileList
    } = this.data;
    console.log("event.detail", event.detail);
    console.log("fileList", this.data.fileList);
    fileList.splice(index, 1); // 删除对应索引的文件
    this.setData({
      fileList
    });
    this.concatenateImageUrls();
  },

  //拼接图片地址
  concatenateImageUrls() {
    const urls = this.data.fileList.map(file => file.url);
    const evaluationImgUrl = urls.join(',');
    console.log("evaluationImgUrl URLs:", evaluationImgUrl);
    this.setData({
      evaluationImgUrl:evaluationImgUrl
    })
  },

  // commentEntity:{
  //   orderId:订单id
  //   satisfiedFlag:1-满意 2-不满意
  //   subSelectMsg:穿戴工整，风雨无阻
  //   subMessage:告诉师傅内容
  //   totalEvaluation:总评
  //   anonymousFlag:0否 1是
  //   serviceEvaluation:服务评价
  //   productEvaluation:商品评价
  //   moreEvaluation:说说怎么样
  //   evaluationImgUrl:商品地址
  //   evaluationVideoUrl:视频地址
  //   }
  //提交
  async clickSubmit() {
    console.log("orderId==========",this.data.orderId);
    const commentEntity={
      orderId:this.data.orderId,
      satisfiedFlag:this.data.satisfiedFlag,
      subSelectMsg:this.data.subSelectMsg,
      subMessage:this.data.subMessage,
      anonymousFlag:this.data.anonymousFlag,
      totalEvaluation:this.data.overallSatisfaction,
      serviceEvaluation:this.data.serviceSatisfaction,
      productEvaluation:this.data.productSatisfaction,
      moreEvaluation:this.data.moreEvaluation,
      evaluationImgUrl:this.data.evaluationImgUrl,
      userId:this.data.worker.userId
    }
    try {
      const res = await request({
        url: indexApi.orderSubmit(),
        method:"POST",
        data: commentEntity
      });
      console.log(res);
      wx.navigateTo({
        url: '/pages/order/index',
      })
    } catch (error) {
      console.error("Error:", error);
    }
  },

})